package com.atjinggu.jinggumail.member;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * @author jingming
 * @Type XsteamUtil.java
 * @Desc
 * @date 2020/12/28 16:41
 */
public class XsteamUtil {
    private static XStream xStream;

    //JVM加载类时会执行这些静态的代码块，如果static代码块有多个，JVM将按照它们在类中出现的先后顺序依次执行它们，每个代码块只会被执行一次。
    static{
        xStream = new XStream(new DomDriver());
        /*
         * 使用xStream.alias(String name, Class Type)为任何一个自定义类创建到类到元素的别名
         * 如果不使用别名，则生成的标签名为类全名
         */
        xStream.alias("test", TestABC.class);
        xStream.alias("abc",AbcTest.class);
//        xStream.alias("address", Address.class);
        //将某一个类的属性，作为xml头信息的属性，而不是子节点
//        xStream.useAttributeFor(TestABC.class, "test");
        //对属性取别名
//        xStream.aliasField("省", Address.class,"province");
    }

    //xml转java对象
    public static Object xmlToBean(String xml){
        return xStream.fromXML(xml);
    }

    //java对象转xml
    public static String beanToXml(Object obj){
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xStream.toXML(obj);
    }

    public static void main(String args[]) {
        long time1  = System.currentTimeMillis();
        //测试java对象转xml，java对象中包含集合对象
        TestABC testABC = new TestABC();
        testABC.setName("nameaaaa");
        testABC.setAge(111);
        testABC.setAddress("addressaaa");
        String xml = XsteamUtil.beanToXml(testABC);
        System.out.println(xml);

//        //测试xml转java对象
//        Person person2 = (Person) XsteamUtil.xmlToBean(xml);
//        System.out.println(person2.getAddress().get(1).getProvince());
//
//        long time2 = System.currentTimeMillis();
//        System.out.println((time2-time1)+"ms");
    }


}